package com.qc.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qc.chat.ChatListMember;
import com.qc.common.DateUtil;
import com.qc.common.Session;
import com.qc.entity.UserEntity;
import com.qc.entity.message.ChatListEntity;
import com.qc.entity.message.ChatMessageEntity;
import com.qc.jpush.JPushUtil;
import com.qc.serverlistener.CacheUtil;
import com.qc.service.MessageService;

import net.sf.json.JSONObject;

@Controller
public class MessageController extends BaseController {

	@Resource
	private MessageService messageService;
	
	/**
	 * 发送消息
	 */
	@RequestMapping(value = "/MobileSendMessage", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileSendMessage(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		ChatMessageEntity entity = (ChatMessageEntity) JSONObject.toBean(JSONObject.fromObject(p1), ChatMessageEntity.class);

		Timestamp createTime = DateUtil.getCurrentSysTimestamp();
		//1，消息入库
		//2,查看内存中是否有了这个人聊天列表
		//3，如果没有就在map中增加一个，如果有就处理一下这个对象，未读数量＋1，最后的时间和最后的内容改变, 最后一条消息类型也要改变(需要把自己的列表最后一条消息和时间 和未读数量都改变)
		//4，把这条消息放到内存
		
		
		entity.setSendTime(DateUtil.timestampParseString(createTime));

		long state = messageService.sendMessage(entity);

		entity.setMsgId(state);
		
		//处理双方聊天列表
		ChatListMember.senderMessage(entity);
		
		JPushUtil.chatPush(entity);
		
		//将map放入到文件
		ChatListMember.getInstance().cacheMapToTxt();
		if (state > 0) {
			return returnSuccessResult(entity);
		}
		return returnFailedResult("发送失败");
	}
	
	/**
	 * 获取聊天列表
	 */
	@RequestMapping(value = "/MobileGetChatList", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileGetChatList(HttpServletRequest request, HttpServletResponse response) {

//		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
//		ChatMessageEntity entity = (ChatMessageEntity) JSONObject.toBean(JSONObject.fromObject(p1), ChatMessageEntity.class);


		List<ChatListEntity> listEntity = ChatListMember.chatListMap.get(userId);
		//防止聊天列表用户已经改了头像和昵称没有即使更新的问题，这里每次都从内存拿最新的头像和昵称
		
		if(listEntity!=null && !listEntity.isEmpty()){
			for (ChatListEntity chatListEntity : listEntity) {
				if(chatListEntity.getTargetId() != 0) {
					UserEntity userEntity = CacheUtil.getUserInfo(chatListEntity.getTargetId());
					chatListEntity.setAvatar(userEntity.getAvatar()); 
					chatListEntity.setNickname(userEntity.getNickname());
				}
				
			}
			
			return returnSuccessResult(listEntity);
		}
		
		return returnSuccessResult("");
	}
	
	/**
	 * 根据客户端拿到的消息设置为已读
	 * p1: 多个消息逗号隔开 (msgId,msgId,2,3,4,5)
	 */
	@RequestMapping(value = "/MobileReadMessage", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileReadMessage(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
//		ChatMessageEntity entity = (ChatMessageEntity) JSONObject.toBean(JSONObject.fromObject(p1), ChatMessageEntity.class);

		String[] msgIdStr = p1.split(",");
		List<Long> msgIdList = new ArrayList<Long>();
		for (String string : msgIdStr) {
			msgIdList.add(Long.valueOf(string));
		}

		List<ChatListEntity> list = ChatListMember.chatListMap.get(userId);
		if(list!=null && !list.isEmpty()){
			
			for (ChatListEntity chatListEntity : list) {
				List<ChatMessageEntity> tempDelList = new ArrayList<ChatMessageEntity>();
				
				for (ChatMessageEntity messageEntity : chatListEntity.getMsgList()) {
					if (msgIdList.contains(messageEntity.getMsgId())) {
						//存在就删除
						tempDelList.add(messageEntity);
					}
				}
				chatListEntity.getMsgList().removeAll(tempDelList);
//				chatListEntity.setUnReadNum(0);
			}
		}
		
		
		
		return returnSuccessResult("消息处理成功");
	}
	
	/**
	 * 获取聊天消息
	 */
	@RequestMapping(value = "/MobileGetChatMessage", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileGetChatMessage(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		ChatMessageEntity entity = (ChatMessageEntity) JSONObject.toBean(JSONObject.fromObject(p1), ChatMessageEntity.class);

		
		List<ChatListEntity> listEntity = ChatListMember.chatListMap.get(userId);
		List<ChatMessageEntity> resultList = null;
		if(listEntity!=null && !listEntity.isEmpty()){
			for (ChatListEntity chatListEntity : listEntity) {
				if (chatListEntity.getTargetId() == entity.getTargetId()) {
					resultList = chatListEntity.getMsgList();
					//未读数量置为0
					chatListEntity.setUnReadNum(0);
					//以后用户多了，应该弄个定时器写。
					ChatListMember.getInstance().cacheMapToTxt();
					break;
				}
			}
			
		}
		if (resultList != null) {
			return returnSuccessResult(resultList);
		}
		return returnSuccessResult("");
	}
	
	/**
	 * 删除聊天列表
	 */
	@RequestMapping(value = "/MobileDelChatList", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileDelChatList(HttpServletRequest request, HttpServletResponse response) {

		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
		ChatListEntity entity = (ChatListEntity) JSONObject.toBean(JSONObject.fromObject(p1), ChatListEntity.class);

		
		List<ChatListEntity> listEntity = ChatListMember.chatListMap.get(userId);
		ChatListEntity delEntity = null;
		if(listEntity!=null && !listEntity.isEmpty()){
			for (ChatListEntity chatListEntity : listEntity) {
				if (chatListEntity.getTargetId() == entity.getTargetId()) {
					delEntity = chatListEntity;
					break;
				}
			}
			if (delEntity != null) {
				listEntity.remove(delEntity);
				//将最新的map放入到文件
				ChatListMember.getInstance().cacheMapToTxt();
			}
		}
		if (delEntity != null) {
			return returnSuccessResult("删除成功");
		}
		return returnSuccessResult("删除失败");
	}
	
	/**
	 * 忽略未读消息(将所有的未读消息清空)
	 */
	@RequestMapping(value = "/MobileIgnoreAllUnreadMessage", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String mobileIgnoreAllUnreadMessage(HttpServletRequest request, HttpServletResponse response) {

//		String p1 = request.getParameter("p1");
		String p2 = request.getParameter("p2");
		long userId = Session.getUserIdfromMobileSession(p2);
		if (userId == 0)
			return returnFailedResult("");
		
//		ChatListEntity entity = (ChatListEntity) JSONObject.toBean(JSONObject.fromObject(p1), ChatListEntity.class);
		
		List<ChatListEntity> listEntity = ChatListMember.chatListMap.get(userId);
		if(listEntity!=null && !listEntity.isEmpty()){
			for (ChatListEntity chatListEntity : listEntity) {
				//未读数量置为0
				chatListEntity.setUnReadNum(0);
				//以后用户多了，应该弄个定时器写。
				ChatListMember.getInstance().cacheMapToTxt();
			}
			
		}

		return returnSuccessResult("忽略所有未读消息成功");
	}
	
	public static void main(String[] args) {
		 
	}
}
